package com.itheima.controller.v1;

import com.itheima.common.MsgResult;
import com.itheima.common.R;
import com.itheima.controller.v1.api.UserControllerApi;
import com.itheima.dto.LoginDto;
import com.itheima.pojo.SysUser;
import com.itheima.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController implements UserControllerApi {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private HttpServletRequest request;

    //用户登录
    @Override
    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto) {
        log.info("获取登录的用户为:"+loginDto);
        //获取生成的验证码
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        //判断登录状态
        R r =sysUserService.login(loginDto,code);
        //5.登录成功,存储到session中
        if (r.getCode()==1){
            SysUser user = (SysUser) r.getData();
            session.setAttribute("userId",user.getUserId());
        }
        //6.返回用户信息即可
        return r;
    }

    //用户注销
    @Override
    @GetMapping("/logout")
    public R logout() {
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
        if (userId!=null){
            session.invalidate();
            log.info("注销成功");
            return new R(1, MsgResult.SUCCESS_LOGOUT,null);
        }else {
            log.info("注销失败");
            return new R(0,MsgResult.WRONG_LOGOUT,null);
        }
    }
}
